using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using SimpleJSON;
using UnityEngine;

namespace Gj.LeanCloud
{
    public class Api
    {

        private static readonly HttpClient client = new HttpClient();
        public static string API_BASE_URL = "https://hkhxfohq.lc-cn-n1-shared.com/1.1";
        public static Api Instance;

        static Api()
        {
            Instance = new Api();
        }

        public static JSONObject BaseHeader()
        {
            var header = new JSONObject();
            header["X-LC-Id"] = LeanCloud.settings.AppId;
            header["X-LC-Key"] = LeanCloud.settings.AppKey;
            API_BASE_URL = LeanCloud.settings.ApiDomain + "/1.1";
            return header;
        }

        public static JSONObject HistoryHeader(string version)
        {
            var header = new JSONObject();
            var app = LeanCloud.settings.Apps.Find((cloudApp => cloudApp.Version == version));
            header["X-LC-Id"] = app.AppId;
            header["X-LC-Key"] = app.AppKey;
            API_BASE_URL = app.ApiDomain + "/1.1";
            return header;
        }

        public static async Task<JSONNode> Get(string url, JSONObject data, JSONObject header = null)
        {
            LogTools.Log($"Get {url} {(data == null ? "empty": data)}");
            var query = "";
            if (data != null && data.Count > 0)
            {
                var e = data.GetEnumerator();
                while (e.MoveNext())
                {
                    var current = (KeyValuePair<string, JSONNode>)e.Current;
                    query += $"{current.Key}={current.Value.Value}&";
                }
                LogTools.Log($"Query {query}");
            }
            var uriBuilder = new UriBuilder(API_BASE_URL+url+"?"+query);
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, uriBuilder.Uri);
            return await Send(requestMessage, header);
        }
        public static async Task<JSONNode> Post(string url, JSONNode data, JSONObject header = null)
        {
            LogTools.Log($"Post {url} {(data == null ? "empty": data)}");
            var content = new StringContent((data == null ? "": data.ToString()), Encoding.UTF8, "application/json");

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, API_BASE_URL+url)
            {
                Content = content
            };
            return await Send(requestMessage, header);
        }
        public static async Task<JSONNode> Put(string url, JSONNode data, JSONObject header = null)
        {
            LogTools.Log($"Put {url} {(data == null ? "empty": data.ToString())}");
            var content = new StringContent((data == null ? "": data.ToString()), Encoding.UTF8, "application/json");

            var requestMessage = new HttpRequestMessage(HttpMethod.Put, API_BASE_URL+url)
            {
                Content = content
            };
            return await Send(requestMessage, header);
        }
        public static async Task<JSONNode> Send(HttpRequestMessage requestMessage, JSONObject header = null)
        {
            // 设置自定义请求头（可以根据需要添加其他 header）
            // content.Headers.Add("Content-Type","application/json");
            if (header != null && header.Count > 0)
            {
                var e = header.GetEnumerator();
                var o = new JSONObject();
                while (e.MoveNext())
                {
                    var current = (KeyValuePair<string, JSONNode>)e.Current;
                    LogTools.Log($"Header {current.Key}: {current.Value.Value}");
                    requestMessage.Headers.Add(current.Key, current.Value.Value);
                }
            }

            var response = await client.SendAsync(requestMessage);
            var responseContent = await response.Content.ReadAsStringAsync();
            var info = JSONNode.Parse(responseContent);
            info["response"] = response.StatusCode.ToString();
            LogTools.Log($"Result: {info}");
            return info;
        }
    }
}